import json

from flask import request, redirect, session
from flask_cors import cross_origin

from app.controller.error_enum import ErrorType
from app.controller.usr import *

logger = log.Logger(__name__)


@usr_module.route('/login', methods=['GET', "POST"])  # 路由默认接收请求方式位POST，然而登录所需要请求都有，所以要特别声明。
@cross_origin(supports_credentials=True)
def login():
    # 获取参数,去除空格以及"   "
    user = request.args.get('usr_account')
    pwd = request.args.get('usr_passwd')
    if user is not None and pwd is not None:
        user = user.strip(" ").strip("\'").strip("\"")
        pwd = pwd.strip(" ").strip("\'").strip("\"")
    else:
        logger.error('参数获取失败, user=%s, pwd=%s' % (user, pwd))
        return render_template("login.html", error="用户名或密码不能为空")

    # check null
    if not user or not pwd:
        return render_template("login.html", error="用户名或密码不能为空")
    # 加密
    pwd = sha256(pwd)

    # 调用service
    # 判断是否登录成功
    user_id = do_login(user, pwd)
    if user_id is None:
        logger.error('用户登录失败, user=%s' % user)
        return {'user_id': None}
    if user_id:
        session['user_id'] = user_id
        # 登录成功，将用户信息存入session
        # session['user_info'] = user
        logger.info('用户登录成功, user=%s' % user_id[0])
        base_info = get_base_info(user_id[0])
        return {'user_id': user_id, 'base_info': base_info}


@usr_module.route('/register', methods=['GET', 'POST'])
@cross_origin(supports_credentials=True)
def register():
    try:
        usr_account = request.args.get('username').strip(" ").strip("\'").strip("\"")
        usr_passwd = request.args.get('password').strip(" ").strip("\'").strip("\"")
        usr_name = request.args.get('nickname').strip(" ").strip("\'").strip("\"")
        usr_email = request.args.get('email').strip(" ").strip("\'").strip("\"")
        usr_phone = request.args.get('phone').strip(" ").strip("\'").strip("\"")
    except Exception as e:
        logger.error('信息填写错误, error=%s' % e)
        return "信息填写错误"
    # check null
    if not usr_account or not usr_passwd or not usr_name or not usr_email or not usr_phone:
        return "注册信息不能为空"
        # return render_template("register.html", error="注册信息不能为空")
    # 加密
    usr_passwd = sha256(usr_passwd)
    # 生成用户实体
    usr = user_entity.User \
        (user_account=usr_account, password=usr_passwd, user_name=usr_name, email=usr_email, phone=usr_phone)

    print(usr.to_string())
    # 判断是否注册成功
    user_id = do_register(usr)
    if user_id:
        # 注册成功，将用户信息存入session
        logger.info('用户注册成功, user=%s' % usr_account)
        session['user_id'] = user_id
        # 返回用户其余基本信息
        base_info = get_base_info(user_id)
        return {'code': 200, 'user_id': user_id, 'base_info': base_info}
    else:
        # 注册失败，返回注册页面
        logger.error('用户注册失败, user=%s' % usr_account)
        return {'code': ErrorType.USER_REGISTER_FAILED.value, 'user_id': '-1'}


@usr_module.route('/index')
@cross_origin(supports_credentials=True)
def index():
    user_info = session.get('user_info')
    if not user_info:
        return redirect('/login')
    return 'hello'


@usr_module.route('/logout')
@cross_origin(supports_credentials=True)
def logout_():
    del session['user_info']
    return redirect('/')


'''
:param{
    "id":int
    "cost"(用户可以投资的金额）：int
    "rate"(投资目标): str (low/mid/high) 
    "risk"(风险承受能力): str (low/mid/high) 
    "time"(可用于投资的时间): str (low/mid/high) 
}
:return{
{
    "welcome_msg":str
    "amount":float
    "trace_profit":float
    "daily_profit":float
    "model_list":arr<Model>
}

'''


@usr_module.route('/profile', methods=['GET', 'POST'])
@cross_origin(supports_credentials=True)
def profile():
    if request.method == 'GET':
        logger.warning("trying to get profile")
        user_id = request.args.get('id')
        logger.warning("user_id is %s" % user_id)
        # user_id = request.args.get('id')
        user_base_info = get_base_info(user_id)
        cost = user_base_info['cost']
        rate = user_base_info['rate']
        risk = user_base_info['risk']
        time = user_base_info['time']
        # checknull
        if user_id is None or cost is None or rate is None or risk is None or time is None:
            logger.error('请完善个人信息')
            return redirect('/home')
        logger.info('正在获取用户信息, user=%s' % user_id)
        logger.info('cost=%s, rate=%s, risk=%s, time=%s' % (cost, rate, risk, time))
        return get_model(user_id, cost, rate, risk, time)

    # 从表单中获取
    try:
        logger.warning("trying to update profile")
        user_id = request.args.get('id')
        cost = request.args.get('cost')
        rate = request.args.get('rate')
        risk = request.args.get('risk')
        time = request.args.get('time')
        # checknull
        if user_id is None or cost is None or rate is None or risk is None or time is None:
            logger.error('用户参数为null')
            return redirect('/home')
            # return render_template("index.html", error="用户传入参数错误")
        # _profile = Profile(user_id, cost, rate, risk, time)
    except:
        logger.error('用户传入参数错误')
        return render_template("index.html", error="用户传入参数错误")
    # 更新数据库
    logger.info('正在更新用户信息, user=%s' % user_id)
    update_base_info(user_id=user_id, cost=cost, rate=rate, risk=risk, time=time,user_name=None,email=None,phone=None,avator=None)
    # 调用service
    # print(get_model(user_id, cost, rate, risk, time))
    return get_model(user_id, cost, rate, risk, time)


# test
def test_register():
    usr = user_entity.User("test", "test", "test", "test", "test")
    do_register(usr)


def test_login():
    usr = do_login("test", "test")
    print(usr)


if __name__ == '__main__':
    test_register()
    test_login()
